package io.renren.modules.oa.controller.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.startup.UserConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties.Env;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.oapi.lib.aes.DingTalkEncryptException;
import com.dingtalk.oapi.lib.aes.DingTalkEncryptor;

import io.renren.common.utils.DateUtils;
import io.renren.common.utils.RedisUtils;
import io.renren.common.utils.dingtalk.DingtalkUtils;
import io.renren.modules.oa.entity.OaPlanConfigEntity;
import io.renren.modules.oa.entity.OaPlanEmployeeEntity;
import io.renren.modules.oa.entity.OaPlanLogEntity;
import io.renren.modules.oa.entity.UserConfigEntity;
import io.renren.modules.oa.redis.DingtalkRedis;
import io.renren.modules.oa.service.OaPlanEmployeeService;
import io.renren.modules.oa.service.OaPlanLogService;
import io.renren.modules.oa.websocket.DingtalkSocket;



/**
 * app 钉钉内部管理系统 api接口
 *
 * @author ziye
 * @email 524748907@qq.com
 * @date 2018-10-26 09:01:20
 */
@RestController
@RequestMapping("api/dingtalk")
public class ApiDingtalkController {
   
	@Autowired
    private OaPlanLogService oaPlanLogService;
	
	@Autowired
    private OaPlanEmployeeService oaPlanEmployeeService;
	
    
    /**
     * 钉钉业务回调接口(审批->请假)
     * http://1o90f54084.iok.la/renren-admin/api/dingtalk/dingtalk_call_back
     * @return
     */
    @SuppressWarnings("unused")
	@RequestMapping("/dingtalk_call_back")
    public void dingtalk_call_back(@RequestBody JSONObject json, HttpServletRequest request, HttpServletResponse response){
    	String merchantId = request.getParameter("merchantId");
    	String signature = request.getParameter("signature");
    	String timestamp = request.getParameter("timestamp");
    	String nonce = request.getParameter("nonce");
    	/**对encrypt进行解密**/
    	DingTalkEncryptor dingTalkEncryptor = null;
    	String plainText = null;
    	try {
    		UserConfigEntity userConfig = DingtalkRedis.getUserConfig(Long.parseLong(merchantId));
    		dingTalkEncryptor = new DingTalkEncryptor(userConfig.getDingToken(), userConfig.getDingAesKey(), userConfig.getDingCorpid());
    	    String encrypt = json.getString("encrypt");
    	    plainText = dingTalkEncryptor.getDecryptMsg(signature, timestamp, nonce, encrypt);
    	    System.out.println(plainText);
    	} catch (DingTalkEncryptException e) {
    	    // TODO Auto-generated catch block
    	    System.out.println(e.getMessage());
    	    e.printStackTrace();
    	}
    	//plainText = "{\"createTime\":1540883694000,\"staffId\":\"manager847\",\"bizCategoryId\":\"leave\",\"EventType\":\"bpms_instance_change\",\"type\":\"start\",\"url\":\"https://aflow.dingtalk.com/dingtalk/mobile/homepage.htm?corpid=ding278cea6787cd42ec&dd_share=false&showmenu=true&dd_progress=false&back=native&procInstId=479b7326-1137-4cf4-ab22-473a598d4397&taskId=&dinghash=approval&dd_from=#approval\",\"title\":\"\u9A6C\u5929\u806A\u7684\u8BF7\u5047\",\"processCode\":\"PROC-EF6YCS6WO2-IPM7J0OATPH1N7HMOELO1-YWEKBQKI-QO7\",\"processInstanceId\":\"479b7326-1137-4cf4-ab22-473a598d4397\",\"corpId\":\"ding278cea6787cd42ec\"}";
    	//https://aflow.dingtalk.com/dingtalk/web/query/designCenter?formUuid=FORM-leave-NJJZLP58HL3HBTO2NJ5X1-AV05OQ8I-2&processCode=PROC-EF6YCS6WO2-IPM7J0OATPH1N7HMOELO1-YWEKBQKI-QO7&dirId=15b7aef2af0aa56aafa434f489aa0c51#/
    	/**对从encrypt解密出来的明文进行处理**/
    	JSONObject plainTextJson = JSONObject.parseObject(plainText);       
    	String eventType = plainTextJson.getString("EventType");
    	switch (eventType){
	    	case "org_user_add"://do something
	    	    break;
	    	case "org_user_modify"://do something
	    	    break;
	    	case "org_user_leave":// do something
	    	    break;
	    	case "bpms_instance_change": //审批
	    		String processCode = plainTextJson.getString("processCode");
	    		//请假模板
	    		if(processCode != null && processCode.equals("PROC-EF6YCS6WO2-IPM7J0OATPH1N7HMOELO1-YWEKBQKI-QO7")){
	    			String processInstanceId = plainTextJson.getString("processInstanceId"); //审批实例id
	    			String processinstance = DingtalkUtils.processinstance(DingtalkRedis.getAccessToken(Long.parseLong(merchantId)), processInstanceId);
	    			JSONObject result = JSONObject.parseObject(processinstance);
	    			if (result.containsKey("errcode") && result.getLong("errcode") == 0L) {
	    				JSONObject processInstance = result.getJSONObject("process_instance");
	    				JSONArray arr = processInstance.getJSONArray("form_component_values").getJSONObject(1).getJSONArray("value");
	    				String userid = processInstance.getString("originator_userid");
	    				System.out.println(arr);
	    				OaPlanConfigEntity planConfig = DingtalkRedis.getPlanConfig(Long.parseLong(merchantId));
    					Date startDate = arr.getDate(0);
    					Date endDate = arr.getDate(1);
    					int days = DateUtils.getDiffDaysTo(startDate, endDate);
    					for (int i = 0; i <= days; i++) {
    						Date currDate = DateUtils.addDateDays(startDate, i);
							OaPlanEmployeeEntity planEmployee = oaPlanEmployeeService.selectByUserid(planConfig.getMerchantId(), userid);
    						OaPlanLogEntity planLog = oaPlanLogService.selectByUserid(userid,"2", DateUtils.getStartTime(currDate), DateUtils.getEndTime(currDate));
    						if(planLog == null){
    							 planLog = new OaPlanLogEntity();
    						}
	    					planLog.setMerchantId(planConfig.getMerchantId());
	    					planLog.setTitle(planConfig.getTitle());
	    					planLog.setName(planEmployee.getName());
	    					planLog.setAvatar(planEmployee.getAvatar());
	    					planLog.setType("2");	
	    					planLog.setUserid(userid);
	    					
	    					
	    					planLog.setCreateTime(currDate);
	    					oaPlanLogService.insertOrUpdate(planLog);
	    					
	    					//
	    					JSONObject msg = new JSONObject();
	    					msg.put("name", planEmployee.getName());
	    					msg.put("planEmployee", planEmployee.getAvatar());
	    					
    						DingtalkRedis.setActive(userid, DateUtils.format(new Date()));
    	    				System.out.println("userid:"+userid+"打卡成功");
    	    				DingtalkSocket.sendAllUser(planConfig.getMerchantId(), DingtalkRedis.getAdInfo(planConfig.getMerchantId()));
						}
	    					
	    			
	    				
	    				
	    				
	    			}
	    		}
	    		break;
	    	case "check_url"://do something
	    	default : //do something
	    	    break;
    	}
    	 
    	/**对返回信息进行加密**/
    	long timeStampLong = Long.parseLong(timestamp);
    	Map<String,String> jsonMap = null;
    	try {
    	    jsonMap = dingTalkEncryptor.getEncryptedMap("success", timeStampLong, nonce);
    	} catch (DingTalkEncryptException e) {
    	    System.out.println(e.getMessage());
    	    e.printStackTrace();
    	}
    	JSONObject result = new JSONObject();
    	result.putAll(jsonMap);   
    	try {
			response.getWriter().append(result.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
    }
    
    

}
